package com.after.saas.file.listener;

import cn.hutool.core.util.StrUtil;
import com.after.saas.common.model.TwoTuple;
import com.after.saas.common.model.bo.CoreDictBO;
import com.after.saas.common.utils.ValidatorUtil;
import com.after.saas.file.domain.vo.ExcelErrorVO;
import com.after.saas.file.utils.DictUtil;
import com.after.saas.file.utils.SpringUtil;
import com.alibaba.excel.context.AnalysisContext;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description
 * @Classname GoodsAnalysisReadEventLissten
 * @Author hjchen
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2022/11/7 18:25
 */
@Data
@Slf4j
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class DictAnalysisReadEventListener extends AbstractReadEventListener<CoreDictBO> {

    private StringRedisTemplate redisTemplate = SpringUtil.getBean(StringRedisTemplate.class);

    @Override
    public Class supportClass() {
        return CoreDictBO.class;
    }

    @Override
    public void checkExcel(List<CoreDictBO> dtoList) {
        for (CoreDictBO dictBO : dtoList) {
            Set<String> errFields = new HashSet<>();
            String validMsg = ValidatorUtil.validateBean(dictBO);
            if (StrUtil.isNotEmpty(validMsg)) {
                errFields.add(validMsg);
            }
//            TwoTuple<String, String> packCode = DictUtil.getRemoteCode(redisTemplate, "TS08", dictBO.getDictType());
//            TwoTuple<String, String> uploadCode = DictUtil.getBaseCode(redisTemplate, "TS05", dictBO.getDictLabel());
//            dictBO.setDictValue(packCode.getLeft());
//            dictBO.setDictLabel(uploadCode.getLeft());
//            if (StrUtil.isEmpty(uploadCode.getLeft())) {
//                errFields.add("字典类别代码/名称不存在,请检查！");
//            }
//            if (StrUtil.isEmpty(packCode.getLeft())) {
//                errFields.add("字典标签代码/名称不存在,请检查！");
//            }
            String errMsg = String.join("、", errFields);
            if (StrUtil.isNotEmpty(errMsg)) {
                ExcelErrorVO errorResponse = new ExcelErrorVO();
                errorResponse.setLineNo(dictBO.getLineNo());
                errorResponse.setErrorMessage(errMsg);
                errorInfo.add(errorResponse);
            }
        }
    }

    @Override
    public void invoke(CoreDictBO dictBO, AnalysisContext context) {
        dictBO.setLineNo(context.readRowHolder().getRowIndex());
        data.add(dictBO);
    }

}
